CREATE function [dbo].[fc_T_NhapXuatMatHang]
 (@idMatHang int)
returns table
as
	return(
		select p.NgayPhieu, 
			CASE 
				WHEN MONTH (p.NgayPhieu)> 9 THEN CAST(p.SoPhieu as varchar(10)) + p.DuoiPhieu + '/' + CAST (MONTH(p.NgayPhieu) as varchar(2)) + '-' + RIGHT(CAST(YEAR(p.NgayPhieu) as varchar(4)), 2)
				ELSE CAST(p.SoPhieu as varchar(10)) + p.DuoiPhieu+ '/0' + CAST (MONTH(p.NgayPhieu) as varchar(2)) + '-' + RIGHT(CAST(YEAR(p.NgayPhieu) as varchar(4)), 2)
			END as PhieuNhap,
			'' as PhieuXuat,
			t.Gia,
			p.LyDoNhapXuat,
			ct.SLTH as SLNhap, 
			0 as SLXuat, 
			ct.SLTH * t.Gia as TienNhap,
			0 as TienXuat,
			0 as SLTon,
			0 as TienTon
		from tblSLNX ct, tblDPNX p, tblTon t 
		where ct.ID_DPNX= p.ID_DPNX and ct.ID_MatHang = @idMatHang and t.ID_MatHang = ct.ID_MatHang
		and p.NX='N'
		union all
		select p.NgayPhieu,
			'' as PhieuNhap ,
			CASE 
				WHEN MONTH (p.NgayPhieu)> 9 THEN CAST(p.SoPhieu as varchar(10)) + p.DuoiPhieu + '/' + CAST (MONTH(p.NgayPhieu) as varchar(2)) + '-' + RIGHT(CAST(YEAR(p.NgayPhieu) as varchar(4)), 2)
				ELSE CAST(p.SoPhieu as varchar(10)) + p.DuoiPhieu+ '/0' + CAST (MONTH(p.NgayPhieu) as varchar(2)) + '-' + RIGHT(CAST(YEAR(p.NgayPhieu) as varchar(4)), 2)
			END as PhieuXuat,
			t.Gia,
			p.LyDoNhapXuat,
			0 as SLNhap, 
			ct.SLTH as SLXuat,
			0 as TienNhap,
			ct.SLTH * t.Gia as TienXuat,
			0 as SLTon,
			0 as TienTon
		from tblSLNX ct, tblDPNX p, tblTon t 
		where ct.ID_DPNX= p.ID_DPNX and ct.ID_MatHang = @idMatHang and t.ID_MatHang = ct.ID_MatHang
		and p.NX='X'
	)